package com.dmwork.common.base.util;

import com.dmwork.common.base.result.ExceptionUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

/**
 * @author helen
 * @since 2019/10/16
 */
@Slf4j
public class JwtUtils {

    //token密钥
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";

    /**
     * 获得密钥实例
     *
     * @return 密钥实例
     */
    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(APP_SECRET);
        return new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
    }

    /**
     * 通过用户基本信息生成jwtToken字符串
     *
     * @param jwtInfo 用户基本信息jwt对象
     * @param expire  token生成后的寿命时长（单位：秒）
     * @return token字符串
     */
    public static String getJwtToken(JwtInfo jwtInfo, int expire) {

        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("dmwork-customer")//主题
                .setIssuedAt(new Date())//颁发时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())//过期时间
                .claim("id", jwtInfo.getId())//用户id
                .claim("name", jwtInfo.getName())//用户名
                .claim("avatar", jwtInfo.getAvatar())//用户头像
                .claim("sign", jwtInfo.getSign())
                .claim("color", jwtInfo.getColor())
                .claim("textColor", jwtInfo.getTextColor())
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();

        return JwtToken;
    }

    /**
     * 判断token是否存在与有效
     *
     * @param jwtToken
     * @return
     */
    public static boolean checkJwtTToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            ExceptionUtils.getMessage(e);
            return false;
        }
        return true;
    }

    /**
     * 判断请求头中的token是否存在与有效
     *
     * @param request
     * @return
     */
    public static boolean checkJwtTToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if (StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取保存其中的用户信息
     *
     * @param request
     * @return
     */
    public static JwtInfo getCustomerInfoByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if (StringUtils.isEmpty(jwtToken))
            return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return new JwtInfo(claims.get("id").toString(), claims.get("name").toString(), claims.get("avatar").toString(), claims.get("sign").toString(), claims.get("color")!=null ?claims.get("color").toString() : null , claims.get("textColor") !=null ? claims.get("textColor").toString() : null);
    }
}
